package com.sc.thread.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Shen Chao on 2018-06-14-014.
 *  4个任务是顺序执行的，SingleThreadExecutor得到的是一个单个的线程，这个线程会保证你的任务执行完成，
 *  如果当前线程意外终止，会创建一个新线程继续执行，这和我们直接创建线程不同，也和newFixedThreadPool(1)不同。
 */
public class SingleThreadExecutor {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 1; i < 5; i++) {
            int temp = i;
            executorService.execute(() -> {
                for (int j = 1; j < 5; j++) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("第" + temp + "次的任务的第" + j + "次执行");
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
        //任务执行完毕，关闭线程池
        executorService.shutdown();
    }
}
